package net.ch2.pc12.tech.ackborn.dao;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import net.ch2.pc12.tech.ackborn.model.BbsArticleModel;
import net.ch2.pc12.tech.ackborn.model.BbsBoardModel;
import net.ch2.pc12.tech.ackborn.model.BbsThreadModel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class CacheDAO extends SQLiteOpenHelper{

	private static final String DB = "ackborn.db";
	private static final int DB_VERSION = 1;
	
	private Context context;
	
	public CacheDAO(Context c){
		super(c,DB,null,DB_VERSION);
		context = c;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		
		StringBuffer buf = new StringBuffer();
		buf.append("create table tt_bbs_board (");
		buf.append("id integer primary key autoincrement");
		buf.append(",board_id text not null");
		buf.append(",board_name text not null");
		buf.append(",category_name text not null");
		buf.append(",category_priority integer not null");
		buf.append(",board_priority integer not null");		
		buf.append(",board_url text not null");
		buf.append(");");
		
		db.execSQL(buf.toString());
		
		buf = new StringBuffer();
		buf.append("create table tt_bbs_thread (");
		buf.append("id integer primary key autoincrement");
		buf.append(",board_id text not null");
		buf.append(",thread_id text not null");
		buf.append(",thread_name text not null");
		buf.append(",dat_name text not null");
		buf.append(",total_count integer not null");	
		buf.append(",read_count integer not null");
		buf.append(",thread_priority integer not null");
		buf.append(");");

		db.execSQL(buf.toString());
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {

	}
	
	public boolean hasBoardListCache(){
		boolean ret = false;
		
		SQLiteDatabase db = getReadableDatabase();
		Cursor c = db.rawQuery("select * from tt_bbs_board", null);
		if(c.getCount() < 1){
			ret = false;
		}else{
			ret = true;
		}
		c.close();
		db.close();
		
		return ret;
	}

	public void storeBbsBoardModelList(List<BbsBoardModel> list) {
		SQLiteDatabase db = getWritableDatabase();
		
		db.beginTransaction();
		
		try{
			db.execSQL("delete from tt_bbs_board");
			
			ContentValues values = new ContentValues();

			for(int i=0;i<list.size();i++){
				BbsBoardModel model = list.get(i);
				values.put("board_id",model.getBoardId() );
				values.put("board_name", model.getBoardName());
				values.put("category_name", model.getGroupName());
				values.put("category_priority",model.getGroupPriority());
				values.put("board_priority", model.getBoardPriority());
				values.put("board_url", model.getBoardUrl());
				db.insert("tt_bbs_board", null, values);				
			}
			
			db.setTransactionSuccessful();
		}catch(Exception e){
		}finally{
			db.endTransaction();
			db.close();
		}
		
	}

	public List<BbsBoardModel> getBbsBoardModelList() {
		
		ArrayList<BbsBoardModel> list = new ArrayList<BbsBoardModel>();

		SQLiteDatabase db = getReadableDatabase();
		
		Cursor c = db.rawQuery("select * from tt_bbs_board order by category_priority,board_priority ", null);
		
		while(c.moveToNext()){
			BbsBoardModel model = new BbsBoardModel();
			
			model.setBoardId(c.getString(c.getColumnIndex("board_id")));
			model.setBoardName(c.getString(c.getColumnIndex("board_name")));
			model.setBoardPriority(c.getInt(c.getColumnIndex("board_priority")));
			model.setGroupPriority(c.getInt(c.getColumnIndex("category_priority")));
			model.setGroupName(c.getString(c.getColumnIndex("category_name")));
			model.setBoardUrl(c.getString(c.getColumnIndex("board_url")));
			list.add(model);
		}
		
		c.close();
		db.close();
		
		return list;
		
	}

	public BbsBoardModel getBbsBoardModel() {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean hasBoardCache(String id) {
		boolean ret = false;
		
		SQLiteDatabase db = getReadableDatabase();
		String sql = "select * from tt_bbs_thread where board_id = '" + id +  "'";
		Cursor c = db.rawQuery(sql, null);
		if(c.getCount() < 1){
			ret = false;
		}else{
			ret = true;
		}
		c.close();
		db.close();
		
		return ret;		
	}

	public void storeBbsThreadModelList(List<BbsThreadModel> list,BbsBoardModel parent) {
		SQLiteDatabase db = getWritableDatabase();
		
		db.beginTransaction();
		
		try{
			db.execSQL("update tt_bbs_thread set thread_priority = -1 where board_id = '" + parent.getBoardId() + "'");
			
			ContentValues values = new ContentValues();

			for(int i=0;i<list.size();i++){
				BbsThreadModel model = list.get(i);
				values.put("thread_name", model.getThreadName());
				values.put("dat_name",model.getDatName());
				values.put("total_count", model.getCount());
				values.put("thread_priority",model.getPriority());
				int cnt = db.update("tt_bbs_thread", values, "board_id = ? and thread_id = ?", new String[]{model.getBoardId(),model.getThreadId()});
				if(cnt < 1){
					values.put("board_id",model.getBoardId() );
					values.put("thread_id", model.getThreadId());
					values.put("read_count", 0);
					db.insert("tt_bbs_thread", null, values);						
				}

			}
			db.setTransactionSuccessful();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.endTransaction();
			db.close();
		}		
	}

	public List<BbsThreadModel> getBbsThreadModelList(
			BbsBoardModel bbsBoardModel) {
		
		ArrayList<BbsThreadModel> list = new ArrayList<BbsThreadModel>();
		
		SQLiteDatabase db = getReadableDatabase();
		
		String sql = "select * from tt_bbs_thread where board_id = '" + bbsBoardModel.getBoardId() + "' ";
		sql+=" order by thread_priority";

		Cursor c = null;
		try{
			c = db.rawQuery(sql, null);
			while(c.moveToNext()){
				BbsThreadModel model = new BbsThreadModel();
				
				model.setBoardId(c.getString(c.getColumnIndex("board_id")));
				model.setThreadName(c.getString(c.getColumnIndex("thread_name")));
				model.setThreadId(c.getString(c.getColumnIndex("thread_id")));
				model.setDatName(c.getString(c.getColumnIndex("dat_name")));
				model.setPriority(c.getInt(c.getColumnIndex("thread_priority")));
				model.setCount(c.getInt(c.getColumnIndex("total_count")));
				model.setReadCount(c.getInt(c.getColumnIndex("read_count")));
				list.add(model);
			}

		}catch(Exception e){
			e.printStackTrace();
		}finally{
			c.close();
			db.close();
		}
		

		
		return list;
	}

	public boolean hasThreadCache(String boardId, String threadId) {
		boolean flg = false;
		String[] files = context.fileList();
		String name = boardId + "_" + threadId + ".log";
		for(int i=0;i<files.length;i++){
			if(name.equals(files[i])){
				flg = true;
				break;
			}
		}
		return flg;
	}

	public void storeBbsArticleModelList(List<BbsArticleModel> list,BbsThreadModel th) {
		OutputStream out = null;
		PrintWriter writer = null;
		try {
			String fileName = th.getBoardId() + "_" + th.getThreadId() + ".log";
			out = context.openFileOutput(fileName, context.MODE_PRIVATE);
			writer = new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
			
			for(int i=0;i<list.size();i++){
				BbsArticleModel model = list.get(i);
				
				StringBuffer buf = new StringBuffer();
				buf.append(model.getNum());
				buf.append("<>");
				buf.append(model.getName());
				buf.append("<>");				
				buf.append(model.getMail());
				buf.append("<>");			
				buf.append(model.getDate());
				buf.append("<>");			
				buf.append(model.getId());
				buf.append("<>");		
				buf.append(model.getBe());
				buf.append("<>");
				buf.append(model.getContents().replace("\n", "<br>"));
				buf.append("\n");
				
				writer.append(buf.toString());
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(writer != null){
				writer.close();
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
	}

	public List<BbsArticleModel> getBbsArticleModelList(
			BbsThreadModel bbsThreadModel) {
		// TODO Auto-generated method stub
		ArrayList<BbsArticleModel> list = new ArrayList<BbsArticleModel>();
		InputStream in = null;
		String fileName = bbsThreadModel.getBoardId() + "_" + bbsThreadModel.getThreadId() + ".log";
		BufferedReader reader = null;
		try {
			in = context.openFileInput(fileName);
			reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
			
			String s = null;
			
			while((s = reader.readLine()) != null){
				BbsArticleModel model = new BbsArticleModel();
				
				String[] nodes = s.split("<>");
				if(nodes.length != 7){
					String sss = null;
				}else{
					int i= 0;
					model.setNum(nodes[i++]);
					model.setName(nodes[i++]);
					model.setMail(nodes[i++]);
					model.setDate(nodes[i++]);
					model.setId(nodes[i++]);
					model.setBe(nodes[i++]);
					model.setContents((nodes[i++]).replace("<br>", "\n"));

					list.add(model);									
				}
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try{
				if(reader != null){
					reader.close();
				}
				if(in != null){
					in.close();
				}
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		
		return list;
	}

}
